package com.iretailer.report.quartz.sendReqularly;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.iretailer.report.model.SendRegularly;
import com.iretailer.report.service.SendRegularlyService;
import org.quartz.CronExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;

import java.time.ZonedDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Auther Bennie
 * @Date 2020/6/15 10:38
 * @Description
 */

@Component
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling
public class SendRegularlyCron implements SchedulingConfigurer {
    private String cron = "0 */5 * * * *";
    private static final Logger log = LoggerFactory.getLogger(SendRegularlyCron.class);
    private final SendRegularlyService sendRegularlyService;
    private final SendRegularlyCronService sendRegularlyCronService;

    public SendRegularlyCron(SendRegularlyService sendRegularlyService, SendRegularlyCronService sendRegularlyCronService) {
        this.sendRegularlyService = sendRegularlyService;
        this.sendRegularlyCronService = sendRegularlyCronService;
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(
                //1.添加任务内容(Runnable)
                () -> {
                    ZonedDateTime now = ZonedDateTime.now();
                    log.error("------ 执行动态定时任务: {} ", now.toLocalDateTime());
                    // 获取所有 启用的发送
                    List<SendRegularly> list = sendRegularlyService.selectSendRegularly(new QueryWrapper<SendRegularly>().eq("Enabled", 1));
                    ZonedDateTime judgeZoneDateTime = now.withSecond(0).withNano(0);
                    Date judgeDate = new Date(judgeZoneDateTime.toInstant().toEpochMilli());
                    Date date = new Date(judgeZoneDateTime.plusMinutes(-1).toInstant().toEpochMilli());
                    // 需要执行发送的任务
                    List<SendRegularly> exectueList = new ArrayList<>();
                    // 拿到所有的 cron 类型
                    Map<String, CronExpression> cronExpressionMap = CronTypeUtil.getCronExpressionMap();
                    for (SendRegularly s : list) {
                        CronExpression cronExpression = cronExpressionMap.get(s.getCronType());
                        if (cronExpression != null) {
                            Date nextDate = cronExpression.getTimeAfter(date);
                            log.error("cronType {}  nexDate: {}", s.getCronType(), nextDate);
                            if (nextDate.equals(judgeDate)) {
                                exectueList.add(s);
                            }
                        } else {
                            log.error("cronTypeId is invalid. {} ", JSON.toJSONString(s));
                        }
                    }
                    sendRegularlyCronService.executeSend(judgeZoneDateTime, exectueList);
                },
                //2.设置执行周期(Trigger)
                triggerContext -> {
                    return new CronTrigger(cron).nextExecutionTime(triggerContext);
                }
        );
    }


}
